<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>教师管理</title>
    <link rel="stylesheet" href="/layui/css/layui.css" />
</head>
<body>

<div style="padding:20px;">
    <!-- 添加查询表单 -->
    <form class="layui-form" id="searchForm" style="margin-bottom: 20px;">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">工号</label>
                <div class="layui-input-inline">
                    <input type="text" name="studentId" placeholder="请输入工号" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">姓名</label>
                <div class="layui-input-inline">
                    <input type="text" name="name" placeholder="请输入姓名" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">专业</label>
                <div class="layui-input-inline">
                    <input type="text" name="major" placeholder="请输入专业" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <button type="button" class="layui-btn" id="btnSearch">查询</button>
                <button type="button" class="layui-btn layui-btn-primary" id="btnReset">重置</button>
            </div>
        </div>
    </form>
    
    <button class="layui-btn layui-btn-normal" id="btnAdd">新增教师</button>
    <table id="teacherTable" lay-filter="teacherTableFilter"></table>
</div>

<!-- 新增/编辑弹窗 -->
<div id="teacherFormLayer" style="display:none; padding:20px;">
    <form class="layui-form" id="teacherForm" lay-filter="teacherForm" style="width: 400px;">
        <input type="hidden" name="id" />
        <div class="layui-form-item">
            <label class="layui-form-label">工号</label>
            <div class="layui-input-block">
                <input type="text" name="studentId" required lay-verify="required" placeholder="请输入工号" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">姓名</label>
            <div class="layui-input-block">
                <input type="text" name="name" required lay-verify="required" placeholder="请输入姓名" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">年龄</label>
            <div class="layui-input-block">
                <input type="number" name="age" required lay-verify="required|number" placeholder="请输入年龄" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">专业</label>
            <div class="layui-input-block">
                <input type="text" name="major" required lay-verify="required" placeholder="请输入专业" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="submit" class="layui-btn layui-btn-normal" lay-submit lay-filter="teacherForm">提交</button>
            </div>
        </div>
    </form>
</div>

<!-- 操作栏模板 -->
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
</script>

<script src="/layui/layui.js"></script>
<script>
    layui.use(['table', 'layer', 'form'], function() {
        var table = layui.table;
        var layer = layui.layer;
        var form = layui.form;
        var $ = layui.$;
        
        // 当前查询参数
        var queryParams = {};

        // 渲染表格
        function loadTable() {
            table.render({
                elem: '#teacherTable',
                url: '/api/teachers',
                method: 'GET',
                where: queryParams, // 添加查询参数
                cols: [[
                    {field: 'id', title: 'ID', width: 60, sort: true},
                    {field: 'studentId', title: '工号', width: 120},
                    {field: 'name', title: '姓名', width: 120},
                    {field: 'age', title: '年龄', width: 80},
                    {field: 'major', title: '专业', width: 150},
                    {title: '操作', toolbar: '#barDemo', width: 160}
                ]],
                page: true, // 开启分页
                limits: [10, 20, 50, 100], // 每页条数的选择项
                limit: 10, // 默认每页显示的数量
                request: {
                    pageName: 'page', // 页码的参数名称
                    limitName: 'limit' // 每页数据量的参数名
                },
                response: {
                    statusName: 'code', // 规定数据状态的字段名称
                    statusCode: 0, // 规定成功的状态码
                    msgName: 'msg', // 规定状态信息的字段名称
                    countName: 'count', // 规定数据总数的字段名称
                    dataName: 'data' // 规定数据列表的字段名称
                },
                parseData: function(res) {
                    return {
                        "code": res.code,
                        "msg": res.msg,
                        "count": res.count,
                        "data": res.data
                    };
                }
            });
        }

        // 初始化表格
        loadTable();

        // 查询按钮点击事件
        $('#btnSearch').click(function() {
            queryParams = {};
            var studentId = $('input[name="studentId"]').val();
            var name = $('input[name="name"]').val();
            var major = $('input[name="major"]').val();
            
            // 只添加有值的查询条件
            if (studentId) {
                queryParams.studentId = studentId;
            }
            if (name) {
                queryParams.name = name;
            }
            if (major) {
                queryParams.major = major;
            }
            
            // 重新加载表格并回到第一页
            table.reload('teacherTable', {
                where: queryParams,
                page: {
                    curr: 1 // 重新从第1页开始
                }
            });
        });

        // 重置按钮点击事件
        $('#btnReset').click(function() {
            $('#searchForm')[0].reset();
            queryParams = {};
            
            // 重新加载表格并回到第一页
            table.reload('teacherTable', {
                where: queryParams,
                page: {
                    curr: 1 // 重新从第1页开始
                }
            });
        });

        // 操作栏监听
        table.on('tool(teacherTableFilter)', function(obj){
            var data = obj.data;
            if(obj.event === 'edit'){
                openForm('编辑教师', data);
            } else if(obj.event === 'delete'){
                layer.confirm('确定删除该教师？', function(index){
                    $.ajax({
                        url: '/api/teachers/' + data.id,
                        type: 'DELETE',
                        success: function(res) {
                            if (res.code === 0) {
                                layer.msg('删除成功');
                                // 重新加载当前页
                                table.reload('teacherTable');
                            } else {
                                layer.msg(res.msg || '删除失败');
                            }
                        },
                        error: function(xhr) {
                            layer.msg('删除失败：' + (xhr.responseJSON?.msg || '服务器错误'));
                        }
                    });
                    layer.close(index);
                });
            }
        });

        // 打开表单弹窗
        function openForm(title, data){
            form.val('teacherForm', data || {});
            layer.open({
                type: 1,
                title: title,
                area: ['450px', '400px'],
                content: $('#teacherFormLayer'),
                success: function(layero, index){
                    form.render();
                },
                end: function(){
                    form.val('teacherForm', {});  // 清空表单
                }
            });
        }

        // 点击新增按钮
        $('#btnAdd').click(function(){
            openForm('新增教师');
        });

        // 表单提交事件
        form.on('submit(teacherForm)', function(data){
            var formData = data.field;
            
            // 验证必填字段
            if (!formData.studentId) {
                layer.msg('请输入工号');
                return false;
            }
            if (!formData.name) {
                layer.msg('请输入姓名');
                return false;
            }
            if (!formData.age) {
                layer.msg('请输入年龄');
                return false;
            }
            // 验证年龄是否为数字且大于等于18
            if (isNaN(formData.age) || parseInt(formData.age) < 18) {
                layer.msg('年龄必须是大于或等于18的数字');
                return false;
            }
            if (!formData.major) {
                layer.msg('请输入专业');
                return false;
            }

            var id = formData.id;
            var loadIndex;
            if(id) {
                // 更新
                loadIndex = layer.load(1); // 显示加载动画
                $.ajax({
                    url: '/api/teachers/' + id,
                    type: 'PUT',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    success: function(res){
                        layer.close(loadIndex); // 关闭加载动画
                        if (res.code === 0) {
                            layer.msg('更新成功');
                            // 重新加载当前页
                            table.reload('teacherTable');
                            layer.closeAll('page');
                        } else {
                            layer.msg(res.msg || '更新失败');
                        }
                    },
                    error: function(xhr) {
                        layer.close(loadIndex); // 关闭加载动画
                        console.error('更新失败:', xhr);
                        layer.msg('更新失败：' + (xhr.responseJSON?.msg || '服务器错误'));
                    }
                });
            } else {
                // 新增
                loadIndex = layer.load(1); // 显示加载动画
                $.ajax({
                    url: '/api/teachers',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    success: function(res){
                        layer.close(loadIndex); // 关闭加载动画
                        if (res.code === 0) {
                            layer.msg('新增成功');
                            // 重新加载当前页
                            table.reload('teacherTable');
                            layer.closeAll('page');
                        } else {
                            layer.msg(res.msg || '新增失败');
                        }
                    },
                    error: function(xhr) {
                        layer.close(loadIndex); // 关闭加载动画
                        console.error('新增失败:', xhr);
                        layer.msg('新增失败：' + (xhr.responseJSON?.msg || '服务器错误'));
                    }
                });
            }
            return false; // 阻止表单跳转
        });
    });
</script>

</body>
</html>
